package com.frame.auth.resource.security.config;

import com.frame.auth.resource.security.annotation.AuthExcludeRequest;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @auther zhangwj
 * @date 2021/4/14 下午8:06
 */
@Configuration
public class PermitAllUrlProperties implements InitializingBean {

    @Resource
    private WebApplicationContext applicationContext;

    private List<String> ignoreUrls = new ArrayList<>();

    @Override
    public void afterPropertiesSet() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);
            // TODO 获取方法上边的注解 后期可加入字段判断
            AuthExcludeRequest method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), AuthExcludeRequest.class);
            Optional.ofNullable(method)
                    .ifPresent(inner -> ignoreUrls.addAll(info.getPatternsCondition().getPatterns()));
            // TODO 获取类上边的注解 后期可加入字段判断
            AuthExcludeRequest controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), AuthExcludeRequest.class);
            Optional.ofNullable(controller)
                    .ifPresent(inner -> ignoreUrls.addAll(info.getPatternsCondition().getPatterns()));
        });
    }

    public List<String> getIgnoreUrls() {
        return ignoreUrls;
    }
}
